package com.objecteffects.ilmp.persist.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.google.inject.Inject;
import com.google.inject.Provider;

import com.objecteffects.ilmp.model.UserEntity;
import com.objecteffects.ilmp.persist.api.IUserEntityDao;
import com.objecteffects.ilmp.util.logger.InjectLogger;

import org.slf4j.Logger;

public class UserEntityDao extends AbstractJpaDao<UserEntity> implements
IUserEntityDao {
    @InjectLogger
    private Logger log;

    @Inject
    UserEntityDao(final Provider<EntityManager> _entityManagerProvider) {
        super(_entityManagerProvider);
    }

    @Override
    public UserEntity findByUserName(final String username) {
        final TypedQuery<UserEntity> query =
            this.getEntityManager()
            .createNamedQuery("UserEntity.findByUserName", UserEntity.class)
                .setParameter("userName", username);

        final List<UserEntity> result = query.getResultList();

        this.log.debug("username: {}, result: {}", username, result);

        if (result.isEmpty()) {
            return null;
        }

        return result.get(0);
    }

    @Override
    public UserEntity refresh(final UserEntity entity) {
        if (this.getEntityManager().contains(entity)) {
            this.log.debug("merging");

            this.getEntityManager().merge(entity);

            return entity;
        }

        this.log.debug("fetching");

        return this.getEntityManager().find(UserEntity.class, entity.getId());
    }

    @Override
    public UserEntity findByHash(final String hash) {
        final EntityManager em = this.getEntityManager();

        final TypedQuery<UserEntity> query =
            em.createNamedQuery("UserEntity.findByHash", UserEntity.class)
                .setParameter("hash", hash);

        final List<UserEntity> result = query.getResultList();

        this.log.debug("hash: {}, result: {}", hash, result);

        if (result.isEmpty()) {
            return null;
        }

        if (result.size() > 1) {
            this.log.warn("returned more than 1 result");
        }

        return result.get(0);
    }
}
